<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <img id="img">
  <script>
    const img = document.getElementById('img')

    // 操作真实 DOM
    class PreLoadImage {
      constructor(imgDOM) {
        // 获取真实 DOM
        this.imgDOM = imgDOM
      }

      // 设置真实 DOM 的 src
      setSrc(imgUrl) {
        this.imgDOM.src = imgUrl
      }
    }

    const imgExample = new PreLoadImage(img)
    console.log(imgExample)

    // 操作 new Image()
    class ProxyImage {
      // 占位图的 url
      static LOADING_URL = '..xxx'

      constructor(targetImage) {
        // PreLoadImage 实例，为了在ProxyImage里调PreLoadImage的方法
        this.targetImage = targetImage
      }

      setSrc(targetUrl) {
        this.targetImage.setSrc(ProxyImage.LOADING_URL)
        const virtualImage = new Image()
        virtualImage.src = targetUrl
        virtualImage.onload = () => {
          this.targetImage.setSrc(targetUrl)
        }
      }
    }

    const proxyImgExample = new ProxyImage(imgExample)
    proxyImgExample.setSrc('实际url')
  </script>
</body>

</html>